package com.thibal.lylo;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class LyloMainActivity extends Activity implements OnKeyListener, OnItemClickListener{
	
	private static final String LYLO_URL = "http://www.lylo.fr";
	
	private static final String TAG = LyloMainActivity.class.getSimpleName();
	
	private ListView mListView;
	
	private ProgressDialog mProgressDialog;
	
	private LyloAdapter lyloAdapter;

	private String mWorking;

	private String mRequestToServeur;
	
	private List<LyloRow> mlyloArrayList;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		lyloAdapter = new LyloAdapter(this);

		mListView = (ListView) findViewById(R.id.listView);
		mListView.setAdapter(lyloAdapter);
		
		mWorking = getString(R.string.work_in_progress);
		mRequestToServeur = getString(R.string.request_to_server);
		
		mProgressDialog = ProgressDialog.show(LyloMainActivity.this, mWorking, mRequestToServeur, true, false);
		
		new SiteParser().execute(LYLO_URL + "/concerts-paris.html");
		
		mListView.setOnKeyListener(this);
		mListView.setOnItemClickListener(this);
	}	

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.ok:
			startActivityForResult(new Intent(this, SearchActivity.class), 1);
			return true;
		case R.id.help:
			View view = getLayoutInflater().inflate(R.layout.help_window, null);
			final Dialog dialog = new Dialog(this);
			dialog.setContentView(view);
			dialog.setCanceledOnTouchOutside(true);
			dialog.setTitle(R.string.help_title);
	        ArrayList<Style> style = new ArrayList<Style>();
	        style.add(new Style(R.drawable.style_0_over, getString(R.string.style_rock)));
	        style.add(new Style(R.drawable.style_1_over, getString(R.string.style_jazz)));
	        style.add(new Style(R.drawable.style_2_over, getString(R.string.style_monde)));
	        style.add(new Style(R.drawable.style_3_over, getString(R.string.style_chanson)));
	        style.add(new Style(R.drawable.style_4_over, getString(R.string.style_electro)));
	        style.add(new Style(R.drawable.style_5_over, getString(R.string.style_groove)));
	        style.add(new Style(R.drawable.style_6_over, getString(R.string.style_reggae)));
	        style.add(new Style(R.drawable.style_enfants_16x16, getString(R.string.style_enfants)));
	        
	        HelpWindowAdapter adapter = new HelpWindowAdapter(this, style);
	        ListView lv = (ListView)view.findViewById(R.id.list);
	        lv.setAdapter(adapter);
			dialog.show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK ) { 
			String[] results = data.getStringArrayExtra("result");
			mProgressDialog = ProgressDialog.show(LyloMainActivity.this, mWorking, mRequestToServeur, true, false);
			Log.d(TAG, LYLO_URL + results[0] + results[1] + ".html" + results[2]);
			new SiteParser().execute(LYLO_URL + results[0] + results[1] + ".html" + results[2]);
		}
	}



	private class SiteParser extends AsyncTask<String, Void, List<LyloRow>> {

		protected List<LyloRow> doInBackground(String... arg) {
			List<LyloRow> result = null;
			try
			{
				LyloParser lyloParser = new LyloParser(new URL(arg[0]));
				result = lyloParser.getLinksByClass("liste");

				//	            for (Iterator<TagNode> iterator = links.iterator(); iterator.hasNext();)
				//	            {
				//	                TagNode divElement = (TagNode) iterator.next();
				//	                output.add(divElement.getText().toString());
				//	            }
			}
			catch(Exception e)
			{
				Log.i(TAG, "Unable to parse site data.", e);
			}
			return result;
		}

		protected void onPostExecute(List<LyloRow> result) {
			mProgressDialog.dismiss();
			if (result != null) {
				mlyloArrayList = result;
				lyloAdapter.setmLyloRowList(result);
				lyloAdapter.notifyDataSetInvalidated();
			}
			else {
				Toast.makeText(LyloMainActivity.this, "Couldn't retrieve data", Toast.LENGTH_SHORT).show();
			}
		}
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_SEARCH) 
		{ 
			startActivityForResult(new Intent(this, SearchActivity.class), 1);
			return true; 
		} 
		return false; 
	}

	@Override
	public void onItemClick (AdapterView<?> parent, View view, int position, long id) 
	{
		LyloRow clickedLyloRow = (LyloRow) lyloAdapter.getItem(position);
		
		String placeToGo = 	clickedLyloRow.getPlaceName() + ", Paris, France";

		Intent intent = new Intent(//
				android.content.Intent.ACTION_VIEW, //
				Uri.parse("geo:0,0?q=" + placeToGo));
		
		startActivity(intent);
	}
	
}